<?php

namespace App\Miya\Middlewares;

use Closure;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class CopyrightSign
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $html = Cache::remember('copyright_sign_html', 24 * 60 * 60, function () {
            $tql = <<<TQL
<!--
本程序由以下企业共同研发,如未授权禁止使用:
%s

本程序已申请软件著作权,违法必究:
%s
-->


TQL;
            $company = implode(',', config('copyright.authorization_company'));
            $serial = array_map(function ($data) {
                $data['name'] = str_pad($data['name'], 70, ' ');
                return sprintf("%s\t%s\t%s", ...array_values($data));
            }, config('copyright.serial'));

            $html = sprintf(
                $tql,
                $company,
                implode(PHP_EOL, $serial));
            return $html;
        });

        $content = $response->content();
        $response->setContent($html . $content);
        return $response;
    }
}
